package com.pkk.cloud.support.oauth2.store.handle;

import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.util.Assert;

/**
 * @author peikunkun<br>
 * @version V1.0<br>
 * @Title: token的管理<br>
 * @Description: <><br>
 * @date 2020/3/18 0018 下午 3:11<br>
 * @URL:[]
 */
@Slf4j
public class OAuth2TokenHandle {


  /**
   * @Author YuanWei
   * @Description 清除token信息
   * @Date 18:04 2019/3/26
   * @Param [tokenStore, request]
   * @Return void
   **/
  public static void reMoveToken(TokenStore tokenStore, HttpServletRequest request) {
    String token = extractToken(request);
    Assert.hasText(token, "token must be set");
    OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token);
    if (existingAccessToken != null) {
      if (existingAccessToken.getRefreshToken() != null) {
        log.info("remove refreshToken!", existingAccessToken.getRefreshToken());
        OAuth2RefreshToken refreshToken = existingAccessToken.getRefreshToken();
        tokenStore.removeRefreshToken(refreshToken);
      }
      log.info("remove existingAccessToken!", existingAccessToken);
      tokenStore.removeAccessToken(existingAccessToken);
    }
  }


  private static String extractToken(HttpServletRequest request) {
    String token = extractHeaderToken(request);
    if (token == null) {
      log.debug("Token not found in headers. Trying request parameters.");
      token = request.getParameter("access_token");
      if (token == null) {
        log.debug("Token not found in request parameters.  Not an OAuth2 request.");
      } else {
        request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, "Bearer");
      }
    }

    return token;
  }

  private static String extractHeaderToken(HttpServletRequest request) {
    Enumeration headers = request.getHeaders("Authorization");

    String value;
    do {
      if (!headers.hasMoreElements()) {
        return null;
      }
      value = (String) headers.nextElement();
    } while (!value.toLowerCase().startsWith("Bearer".toLowerCase()));

    String authHeaderValue = value.substring("Bearer".length()).trim();
    request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, value.substring(0, "Bearer".length()).trim());
    int commaIndex = authHeaderValue.indexOf(44);
    if (commaIndex > 0) {
      authHeaderValue = authHeaderValue.substring(0, commaIndex);
    }

    return authHeaderValue;
  }
}
